﻿namespace Angle.Application
{
    using System;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Threading.Tasks;

    using Angle.Core.Stroes.Users;

    using Skymate.Authorization;
    using Skymate.Authorization.Stors;
    using Skymate.Domain.Specifications;

    public class PermissionChecker:IPermissionChecker
    {
        private readonly IUserStore userStore;

        private readonly IRoleSystemFunctionStore roleSystemFunctionStore;

        public PermissionChecker(IUserStore userStore, IRoleSystemFunctionStore roleSystemFunctionStore)
        {
            this.userStore = userStore;
            this.roleSystemFunctionStore = roleSystemFunctionStore;
        }

        public Task<bool> IsGrantedAsync(string permissionName)
        {
            throw new NotImplementedException();
        }

        public Task<bool> IsGrantedAsync(Guid userId, string permissionName)
        {
            var user = this.userStore.GetByKey(userId);

            var roleds = user.Roles.Select(u => u.ID);

            var stringComper = StringComparer.OrdinalIgnoreCase;

            var isExist =
                this.roleSystemFunctionStore.Exists(
                    Specification<RoleSystemFunction>.Eval(u => roleds.Contains(u.Role.ID))
                        .And(
                            Specification<RoleSystemFunction>.Eval(
                                u => stringComper.Compare(u.SystemFunction.FunctionCode, permissionName) == 0))
                        .And(Specification<RoleSystemFunction>.Eval(u => u.AuthorityLevel != AuthorityLevel.Forbidden)));

            return Task.Run(() => isExist);
        }
    }
}